<template>
	<cl-crud ref="crud" @load="onLoad" :on-refresh="onTableRefresh('cus_name')">
		<cl-pagefull @resize="onResize">
			<template #head>
				<cl-title-module
					:print="printParams"
					:border="false"
					align="top"
					:columns="initColumns"
					v-model="table.columns"
					@export-file="exportExcel"
				>
					<el-row type="flex">
						<cl-filter-group v-model="search">
							<cl-filter label="所属事业部">
								<cl-select
									v-model="search.biz_id"
									placeholder="请选择"
									filterable
									@change="changeBiz"
									style="width: 220px"
								>
									<el-option
										v-for="item in business"
										:key="item.biz_id"
										:label="item.biz_name"
										:value="item.biz_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="品牌">
								<cl-select
									v-model="search.bra_id"
									placeholder="全部"
									filterable
									clearable
									multiple
									collapse-tags
									style="width: 220px"
								>
									<el-option
										v-for="item in bizRefData.brand"
										:key="item.bra_id"
										:label="item.bra_name"
										:value="item.bra_id"
									/>
								</cl-select>
							</cl-filter>

							<cl-filter label="打款时间">
								<cl-date-picker
									v-model="search.time2"
									type="daterange"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="yyyy-MM-dd"
									style="width: 210px"
								/>
							</cl-filter>
							<cl-filter label="所属部门">
								<cl-cascader
									clearable
									v-model="search.dept_ids"
									:options="deptList"
									collapse-tags
									style="min-width: 230px"
									:props="{
										multiple: true,
										value: 'dept_id',
										label: 'dept_name'
									}"
									filterable
									@change="changeDept"
								/>
							</cl-filter>
							<cl-filter label="所属门店">
								<cl-shop-select
									v-model="search.store_id"
									placeholder="请选择"
									filterable
									clearable
									show-all
									:biz_id="search.biz_id"
								/>
							</cl-filter>
							<cl-filter label="下定时间">
								<cl-date-picker
									v-model="search.time"
									type="daterange"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="yyyy-MM-dd"
									style="width: 210px"
								/>
							</cl-filter>
							<cl-filter label="所属人员">
								<cl-select
									v-model="search.user_id"
									placeholder="请选择"
									filterable
									style="width: 210px"
									clearable
								>
									<el-option label="全部" value="" />
									<el-option
										v-for="item in userList"
										:key="item.user_id"
										:label="item.user_name"
										:value="item.user_id"
									/>
								</cl-select>
							</cl-filter>

							<cl-filter label="来源渠道">
								<cl-select
									v-model="search.channel_id"
									placeholder="请选择"
									filterable
									style="width: 210px"
									clearable
								>
									<el-option label="全部" value="" />
									<el-option
										v-for="item in sourceList"
										:key="item.id"
										:label="item.cname"
										:value="item.id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="退定时间">
								<cl-date-picker
									v-model="search.time1"
									type="daterange"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="yyyy-MM-dd"
									style="width: 210px"
								/>
							</cl-filter>
							<cl-filter label="审核状态">
								<cl-select
									v-model="search.status"
									placeholder="请选择"
									style="width: 150px"
									clearable
								>
									<el-option label="全部" value="" />
									<el-option
										v-for="(item, index) in optionsStatus"
										:key="index"
										:label="item.label"
										:value="item.value"
									>
									</el-option>
								</cl-select>
							</cl-filter>

							<cl-filter label="客户关键字">
								<el-input
									v-model="search.cus_name"
									placeholder="手机号/微信号/客户名称/会员号"
									clearable
									style="width: 220px"
								/>
							</cl-filter>
							<cl-filter label="退订来源">
								<cl-select
									v-model="search.source_model"
									placeholder="请选择"
									style="width: 150px"
									clearable
								>
									<el-option label="全部" value="0" />
									<el-option label="系统退订" value="1" />
									<el-option label="落地页退订" value="2" />
								</cl-select>
							</cl-filter>
							<cl-filter label="退订方式">
								<cl-select
									v-model="search.order_id"
									placeholder="请选择"
									style="width: 150px"
									clearable
								>
									<el-option label="全部" value="" />
									<el-option label="银联退货" value="1" />
									<el-option label="售后退订" value="2" />
								</cl-select>
							</cl-filter>

							<!-- <el-button
								v-if="search.status == 3"
								type="warning"
								@click="handleRemit()"
							>
								一键打款
							</el-button> -->
						</cl-filter-group>

					</el-row>
				</cl-title-module>
				<div style="position: absolute; top: 50px; right: 28px">
					<el-button @click="jumpToDeposit()">跳转到退定列表</el-button>
				</div>
			</template>
			<cl-table id="afterRefundapp" v-bind="table">
				<template #column-yn="{ scope: { row } }">
					<template v-if="row.yn == 1 && row.again_time > 0">
						待审核（重新退回）
					</template>
					<template v-else>
						{{ row.yn | filterYn }}
					</template>
				</template>
				<template #column-opt="{ scope: { row } }">
					<div class="flex flex-align-start">
						<el-button type="primary" @click="openDetail(row)"> 详情 </el-button>
						<el-button
							type="danger"
							v-auth="'store_cusdetailindex_look'"
							@click="openCusDetail(row)"
						>
							查看
						</el-button>
						<el-dropdown
							class="ml-1"
							size="medium"
							v-if="![0, 4, 5].includes(row.yn)"
							v-auth="'store_aftersale_refundapp_opt_more'"
							@command="command => onCommand(command, row)"
						>
							<el-button>
								更多<i class="el-icon-arrow-down el-icon--right" />
							</el-button>
							<el-dropdown-menu slot="dropdown">
								<el-dropdown-item command="approve">{{
									row.yn == 1 ? "售后通过" : ""
								}}</el-dropdown-item>
								<template>
									<el-dropdown-item command="reject">驳回</el-dropdown-item>
									<el-dropdown-item command="recover" v-if="row.yn != 3"
										>恢复</el-dropdown-item
									>
								</template>
								<el-dropdown-item command="remit" v-if="row.yn == 3"
									>打款</el-dropdown-item
								>
							</el-dropdown-menu>
						</el-dropdown>
					</div>
				</template>
				<cl-empty slot="empty" />
			</cl-table>
			<template #foot>
				<el-row type="flex">
					<cl-flex1 />
					<zm-pagination />
				</el-row>
			</template>
		</cl-pagefull>
		<!-- 详情 -->
		<refund-detail ref="detail" />
		<!-- 打款 -->
		<refund-remit ref="remit" @success="refresh" />
	</cl-crud>
</template>

<script>
import { exportExcelCoustom } from "@/utils/excel";
import { cloneDeep } from "cl-admin/utils";
import { mapState } from "vuex";
import { delEmptyChildren } from "@/utils";
import RefundDetail from "./components/refund-detail";
import RefundRemit from "./components/refund-remit";
import pageMinix from "@/mixins/page"
import dayjs from "dayjs";

const statusType = {
	0: { text: "已驳回" },
	1: { text: "待审核" },
	3: { text: "未打款" },
	4: { text: "已打款" },
	5: { text: "已恢复" }
};
const filterYn = (val, key = "text") => {
	return statusType[val] ? statusType[val][key] : "";
};
export default {
	name: "AfterOnsalerefundapp",
	inject: ["$layout"],
	mixins: [pageMinix],
	components: {
		RefundDetail,
		RefundRemit
	},
	data() {
		return {
			printParams: {
				id: "afterRefundapp",
				popTitle: "退定金申请"
			},
			search: {
				cus_name: "",
				source_model: "0",
				order_id: "",
				// dept_id: "",
				dept_ids: [],
				store_id: "",
				bra_id: [],
				biz_id: "", //事业部
				user_id: "", // 所属人员
				channel_id: "", // 来源渠道
				time: [], // 下定时间
				time1: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")], // 退定时间
				time2: [], // 打款时间
				status: "" // 审核状态
			},
			optionsStatus: [
				{ value: 1, label: "待审核" },
				{ value: 3, label: "未打款" },
				{ value: 4, label: "已打款" },
				{ value: 5, label: "已恢复" },
				{ value: 0, label: "已驳回" }
			],
			table: {
				"context-menu": ["refresh"],
				columns: [],
				props: {
					maxHeight: 500
				}
			},
			initColumns: [
				{
					label: "序号",
					type: "index",
					prop: "index",
					width: 50,
					fixed: true,
					disable: true
				},
				{ label: "下定时间", prop: "dep_date", minWidth: 100 },
				{ label: "退定时间", prop: "back_date", minWidth: 100 },
				{ label: "打款时间", prop: "pay_date", minWidth: 100 },
				{
					label: "退款原因",
					prop: "back_why",
					minWidth: 150,
					align: "left",
					showOverflowTooltip: true
				},

				{
					label: "品牌",
					prop: "bra_name",
					minWidth: 100,
					align: "left",
					showOverflowTooltip: true
				},
				{
					label: "平台",
					prop: "source_name",
					minWidth: 100,
					align: "left",
					showOverflowTooltip: true
				},
				{
					label: "门店",
					prop: "dept_name",
					minWidth: 120,
					align: "left",
					showOverflowTooltip: true
				},
				{ label: "会员号", prop: "cus_id", width: 120 },
				{
					label: "客户名称",
					prop: "cus_name",
					minWidth: 100,
					align: "left",
					showOverflowTooltip: true
				},
				{ label: "原金额（￥）", prop: "dep_amount", minWidth: 120 },
				{ label: "退定金额（￥）", prop: "back_money", minWidth: 120 },
				{
					label: "归属人",
					prop: "id_add_user_name",
					minWidth: 100,
					align: "left",
					showOverflowTooltip: true
				},
				{ label: "审核状态", prop: "yn", minWidth: 120 },
				{
					label: "打款状态",
					minWidth: 100,
					prop: "payment_status",
					formatter: row => (row.yn == 4 ? "已打款" : "未打款")
				},
				{
					label: "退回状态",
					minWidth: 100,
					prop: "return_status",
					formatter: row => (row.yn == 4 ? "已退回" : row.yn == 5 ? "" : "退回中")
				},
				{
					label: "退订来源",
					minWidth: 100,
					prop: "source_model",
					formatter: row => (row.source_model == 0 ? "全部" : row.source_model == 1 ? "系统退订" : row.source_model == 2 ? "落地页退订" : "-")
				},
				{
					label: "退订方式",
					minWidth: 100,
					prop: "order_id_type",
					formatter: row => row.order_id ? "银联退货" : "售后退订"
				},
				{
					label: "银联流水单号",
					minWidth: 150,
					prop: "order_id"
				},
				{ label: "操作", prop: "opt", width: 230, fixed: "right", disable: true }
			],
			deptList: [],
			userList: [],
			sourceList: []
		};
	},
	filters: {
		filterYn
	},
	computed: {
		...mapState("common", ["visibleCusDetail", "cusFormSubmit"]),
		bizRefData() {
			let { biz_id } = this.search;
			return this.getBizRefData(biz_id);
		}
	},
	watch: {
		visibleCusDetail(v) {
			if (!v && this.zmComponentIsActive) {
				this.refresh();
			}
		},
		cusFormSubmit(v) {
			if (v && this.zmComponentIsActive) {
				this.refresh();
			}
		}
	},
	created() {
		this.search.biz_id = this.getCurrBiz();
		const { initColumns } = this;
		this.init();
		this.table.columns = cloneDeep(initColumns);
	},
	methods: {
		filterYn,
		onLoad({ ctx, app }) {
			ctx.service(this.$service.deposit)
				.set("dict", {
					api: {
						page: "refundlist"
					}
				})
				.done();
			app.refresh(this.search);
		},
		// crud刷新
		refresh() {
			this.$refs.crud.refresh({ page: 1, ...this.search });
		},
		onResize(h) {
			this.table.props.maxHeight = h;
		},
		init() {
			const { biz_id } = this.search;
			this.getBizRefBrand(biz_id);
			this.initData();
		},
		initData() {
			this.getDeptList();
			this.getSourceList();
			this.getUserList();
		},
		changeBiz() {
			this.search = {
				...this.search,
				bra_id: [],
				dept_ids: [],
				store_id: "",
				user_id: "",
				channel_id: ""
			};
			this.init();
			// this.refresh();
		},
		changeDept() {
			this.search.user_id = "";
			this.getUserList();
			// this.refresh();
		},
		//查看
		openCusDetail(row) {
			this.$layout.openCusDetail(row, "earnest");
		},
		// 详情
		openDetail(row) {
			this.$refs.detail.open(row);
		},
		handleRemit() {
			this.confirm("此操作将会打款所有未打款的退定, 是否继续?")
				.then(async () => {
					await this.$service.deposit.togetherPayment({ back_date: this.search.time2 });
					this.$message.success("操作成功");
					this.refresh();
				})
				.catch(() => {});
		},
		// 更多
		onCommand(command, row) {
			if (command === "remit") {
				this.$refs.remit.open(row);
				return;
			}
			this[command](row);
		},
		// 通过
		approve(row) {
			this.optConfirm({
				title: "通过",
				label: "通过备注",
				placeholder: "请输入通过备注",
				row,
				yn: 3
			});
		},
		// 驳回
		reject(row) {
			this.optConfirm({
				title: "驳回",
				label: "驳回原因",
				placeholder: "请输入驳回原因",
				row,
				yn: 0
			});
		},
		// 恢复
		recover(row) {
			this.optConfirm({
				title: "恢复",
				label: "恢复备注",
				placeholder: "请输入恢复备注",
				row,
				yn: 5
			});
		},
		// 操作确认
		optConfirm({ title, label, placeholder, message, row, yn }) {
			this.$crud.openForm({
				title,
				width: "500px",
				props: { "label-position": "top" },
				items: [
					{
						label,
						prop: "back_why",
						component: {
							name: "el-input",
							attrs: { placeholder },
							props: { type: "textarea", rows: 3 }
						}
						// rules: {
						// 	required: true,
						// 	message: message || placeholder
						// }
					}
				],
				op: { saveButtonText: "提交" },
				on: {
					submit: async (data, { close, done }) => {
						try {
							const { dep_id } = row;
							await this.$service.deposit.operaterefunduse({
								...data,
								dep_id,
								yn
							});
							this.$message.success("操作成功");
							this.refresh();
							close();
						} catch (error) {
							console.log(error);
							done();
						}
					}
				}
			});
		},
		// 部门
		async getDeptList() {
			const { biz_id } = this.search;
			this.deptList = delEmptyChildren(
				(await this.$store.dispatch("common/getDept", {
					biz_id,
					needAll: false,
					needCascader: true
				})) || []
			);
		},
		// 获取归属人列表
		async getUserList() {
			const { biz_id } = this.search;
			let dept_id = this.search.dept_ids.join();
			this.userList = [];
			if (!biz_id) return;
			const data = await this.$service.user.deptuserlists({
				biz_id,
				dept_id
				// post: 1
			});
			this.userList = data;
		},
		//获取来源渠道
		async getSourceList() {
			const { biz_id } = this.search;
			this.sourceList = [];
			if (!biz_id) return;
			const data = await this.$service.source.list({ biz_id });
			this.sourceList = data;
		},
		async exportExcel() {
			// exportExcel("#afterRefundapp");
			const loading = this.$loading({
				lock: true,
				text: "正在下载报表中~"
			});
			const query = {
				...this.search,
				all_page: 1
			};
			const { list } = await this.$service.deposit.refundlist(query).catch(e => {
				loading.close();
				throw e;
			});
			console.log("list", list);
			if (list?.length > 0) {
				const newList = list.map((row, index) => {
					return {
						...row,
						index: index + 1,
						yn: row.yn == 4 ? "已打款" : "未打款",
						payment_status: row.yn == 4 ? "已打款" : "未打款",
						return_status: row.yn == 4 ? "已退回" : row.yn == 5 ? "" : "退回中",
						order_id_type: row.order_id ? "银联退货" : "系统退订"
					};
				});
				console.log(newList);
				exportExcelCoustom("退定金列表", newList, this.initColumns);
			}
			loading.close();
		},
		jumpToDeposit() {
			this.$router.push('/home/cus/mine/getEarnest?type=refund')
		}
	}
};
</script>

<style lang="scss" scoped>
::v-deep {
	.title-module {
		margin-bottom: 0;
		padding-bottom: 0;
		&::-webkit-scrollbar {
			height: 6px;
		}
		&::-webkit-scrollbar-thumb {
			background-color: rgba(144, 147, 153, 0.3);
			border-radius: 5px;
		}
		&::-webkit-scrollbar-track {
			background: transparent;
		}
	}
}
</style>
